const deviceModel = require('../model/device');
const channelModel = require('../model/channel');
const deviceCache = require("../db/deviceCache");
const log4js = require('../utils/logUtils');
const logger = log4js.getLogger('service');
const config = require("../db/config");
const settingModel = require("../model/setting");

const TAG = "[DbHandler Service]";
// TODO: 改到deviceCache里去
module.exports = {
    /**
     * 从数据库加载设备缓存信息,如果没加载到返回空
     * @param {*} deviceid 设备号
     */
    loadDevice: async function (deviceid) {
        const sipSetting = await settingModel.load();

        if (!deviceCache.registry[deviceid] || !deviceCache.registry[deviceid].channels) {
            // 从数据库加载
            let deviceInfoInDb = await deviceModel.getDeviceByDeviceId(deviceid);

            if (deviceInfoInDb) {
                // 取channel列表
                const channelList = await channelModel.list(deviceid);
                deviceInfoInDb.channels = {};
                channelList.map((item) => {
                    deviceInfoInDb.channels[item.deviceid] = deviceModel.generateEmptyChannel(deviceInfoInDb, item.deviceid);
                })
                const obj = Object.assign({
                    deviceid, session: {
                        realm: sipSetting.server_realm
                    }
                }, deviceInfoInDb);
                if (!obj.protocol) {
                    obj.protocol = 'UDP';
                }
                deviceCache.registry[deviceid] = obj;
            }

        }
        return (deviceCache.registry[deviceid]);
    }
};
